﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using System.Reflection;

namespace ExtensionHelper.Json
{
    public class JsonHelper
    {
        /// <summary>
        /// 获得Json解析后数据
        /// </summary>
        /// <param name="jsonText"></param>
        /// <returns></returns>
        public static string GetJsonStr(object obj)
        {
            if (obj == null)
            {
                return null;
            }

            JsonSerializerSettings jss = new JsonSerializerSettings();
            jss.Formatting = Formatting.Indented;
            jss.DefaultValueHandling = DefaultValueHandling.Include;
            jss.NullValueHandling = NullValueHandling.Ignore;
            jss.DateFormatHandling = DateFormatHandling.IsoDateFormat;

            return JsonConvert.SerializeObject(obj, jss);
        }
        /// <summary>
        /// 获得Json解析后数据
        /// </summary>
        /// <param name="jsonText"></param>
        /// <returns></returns>
        public static T GetObject<T>(string jsonText)
        {
            T data = default(T);
            if (string.IsNullOrEmpty(jsonText))
            {
                return data;
            }
            try
            {
                JsonSerializerSettings jss = new JsonSerializerSettings();
                jss.Formatting = Formatting.Indented;
                jss.DefaultValueHandling = DefaultValueHandling.Include;
                jss.NullValueHandling = NullValueHandling.Ignore;
                jss.DateFormatHandling = DateFormatHandling.IsoDateFormat;

                data = JsonConvert.DeserializeObject<T>(jsonText, jss);
            }
            catch
            {
                return data;
            }
            return data;
        }

        /// <summary>
        /// 反序列化JSON到给定的匿名对象.
        /// </summary>
        /// <typeparam name="T">匿名对象类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <param name="anonymousTypeObject">匿名对象</param>
        /// <returns>匿名对象</returns>
        public static T GetAnonymousObject<T>(string json, T anonymousTypeObject)
        {
            T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
            return t;
        }
    }
}
